package com.stylefeng.guns.modular.vpn_package_info.service.impl;

import com.stylefeng.guns.core.common.constant.DatasourceEnum;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.mutidatasource.annotion.DataSource;
import com.stylefeng.guns.modular.system.model.PackageList;
import com.stylefeng.guns.modular.system.model.VpnPackageInfo;
import com.stylefeng.guns.modular.system.dao.VpnPackageInfoMapper;
import com.stylefeng.guns.modular.vpn.dto.PackageDTO;
import com.stylefeng.guns.modular.vpn.utils.LogUtil;
import com.stylefeng.guns.modular.vpn.utils.TimeUtil;
import com.stylefeng.guns.modular.vpn.vo.Paging;
import com.stylefeng.guns.modular.vpn_package_info.bo.FilterBO;
import com.stylefeng.guns.modular.vpn_package_info.dao.DiscountMapper;
import com.stylefeng.guns.modular.vpn_package_info.dto.AddDiscountDTO;
import com.stylefeng.guns.modular.vpn_package_info.dto.PackageInfoDTO;
import com.stylefeng.guns.modular.vpn_package_info.entity.VpnPackageItemDO;
import com.stylefeng.guns.modular.vpn_package_info.service.IVpnPackageInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2020-03-02
 */
@Service
public class VpnPackageInfoServiceImpl extends ServiceImpl<VpnPackageInfoMapper, VpnPackageInfo> implements IVpnPackageInfoService {
    @Autowired
    private VpnPackageInfoMapper packageInfoMapper;

    @Resource
    private DiscountMapper discountMapper;


    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Transactional
    public void updatePackageStatus(Integer packageId,Integer status) {
        packageInfoMapper.updatePackageStatus(packageId,status);
        LogUtil.saveOperationLog("修改套餐状态","修改套餐ID： "+packageId+"，状态为："+(status == 1?"启用":"禁用"));
    }

    /**
     * 添加一个套餐
     * @param dto
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public void addPackage(PackageDTO dto) {
        if (dto.getShowSort() == 0){
            throw new GunsException(BizExceptionEnum.VPN_PACKAGE_SHOW_SORT_ERROR);
        }

        List<VpnPackageItemDO> packageList  = discountMapper.findPackageCountBySort(dto.getShowSort());
        if (packageList != null && packageList.size() > 0){
            throw new GunsException(BizExceptionEnum.VPN_PACKAGE_SHOW_SORT_EXIST);
        }

        VpnPackageInfo packageInfo = new VpnPackageInfo();
        BeanUtils.copyProperties(dto,packageInfo);
        packageInfo.setPriceUnit("1");
        packageInfo.setActualPriceUnit("2");
        if (StringUtils.isEmpty(dto.getAppleProductId())){
            packageInfo.setAppleProductId(System.currentTimeMillis()+"");
        }

        super.baseMapper.insert(packageInfo);
        LogUtil.saveOperationLog("添加套餐",
                "添加"+packageInfo.getPackageName()+"套餐，价格为："+packageInfo.getHkPrice()+"港币");

    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Transactional
    public void updatePackage(PackageInfoDTO dto) {
        if (dto.getShowSort() == 0){
            throw new GunsException(BizExceptionEnum.VPN_PACKAGE_SHOW_SORT_ERROR);
        }

        List<VpnPackageItemDO> packageList = discountMapper.findPackageCountBySort(dto.getShowSort());
        if (packageList != null && packageList.size() > 0 && !packageList.get(0).getId().equals(dto.getId())){
            throw new GunsException(BizExceptionEnum.VPN_PACKAGE_SHOW_SORT_EXIST);
        }

        VpnPackageInfo packageInfo = new VpnPackageInfo();
        BeanUtils.copyProperties(dto,packageInfo);
        packageInfo.setPriceUnit("1");
        packageInfo.setActualPriceUnit("2");


        if (dto.getDiscount() >= 1 || dto.getDiscount() < 0){
            throw new GunsException(BizExceptionEnum.VPN_PACKAGE_DISCOUNT_PARAM_ERROR);
        }else if (dto.getDiscount() != 0){
            if (StringUtils.isEmpty(dto.getHintZh())
                    || StringUtils.isEmpty(dto.getHintEn())
                    || StringUtils.isEmpty(dto.getHintTw())){
                throw new GunsException(BizExceptionEnum.VPN_PACKAGE_DISCOUNT_HINT_ERROR);
            }else if (StringUtils.isEmpty(dto.getStartTime())
                    || StringUtils.isEmpty(dto.getEndTime())){
                throw new GunsException(BizExceptionEnum.VPN_PACKAGE_DISCOUNT_TIME_ERROR);
            }
        }

        super.baseMapper.updateById(packageInfo);

        if (dto.getDiscountId() != null){
            AddDiscountDTO discountDTO = new AddDiscountDTO();
            BeanUtils.copyProperties(dto,discountDTO);
            discountDTO.setPackageId(dto.getId());
            discountDTO.setDiscountPrice(dto.getPrice() * dto.getDiscount());
            discountDTO.setDiscountHkPrice(dto.getHkPrice() * dto.getDiscount());
            try {
                if (TimeUtil.compareTo(discountDTO.getStartTime(),discountDTO.getEndTime())){
                    throw new GunsException(BizExceptionEnum.VPN_PACKAGE_DISCOUNT_TIME_ERROR);
                }

                //1、判断提交的时间是否需要修改状态
                //开始时间、
                if (TimeUtil.compareTo(discountDTO.getStartTime(),new Date())){
                    //大于当前时间，状态改为未激活
                    discountDTO.setStatus(2);
                }else {
                    if(TimeUtil.compareTo(discountDTO.getEndTime(),new Date())){
                        //新改结束时间大于当前时间，状态改为生效
                        discountDTO.setStatus(1);
                        if (dto.getDiscountStatus() != 1){
                            discountDTO.setStartTime(TimeUtil.dateToGTMString(new Date(),"yyyy-MM-dd HH:mm:ss"));
                        }
                    }else{
                        //新改结束时间小于当前时间，状态改为失效
                        discountDTO.setStatus(0);
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

            discountMapper.updateDiscountById(discountDTO);
        }else{

            if(dto.getDiscount() != 0){
                AddDiscountDTO addDto = new AddDiscountDTO();
                addDto.setPackageId(dto.getId());
                addDto.setStatus(1);
                addDto.setDiscount(dto.getDiscount());
                addDto.setDiscountPrice(dto.getPrice() * dto.getDiscount());
                addDto.setDiscountHkPrice(dto.getHkPrice() * dto.getDiscount());
                addDto.setStartTime(dto.getStartTime());
                addDto.setEndTime(dto.getEndTime());
                addDto.setHintZh(dto.getHintZh());
                addDto.setHintEn(dto.getHintEn());
                addDto.setHintTw(dto.getHintTw());
                try {
                    if (TimeUtil.compareTo(addDto.getStartTime(),addDto.getEndTime())){
                        throw new GunsException(BizExceptionEnum.VPN_PACKAGE_DISCOUNT_TIME_ERROR);
                    }

                    //1、判断提交的时间是否需要修改状态
                    //开始时间、
                    if (TimeUtil.compareTo(addDto.getStartTime(),new Date())){
                        //大于当前时间，状态改为未激活
                        addDto.setStatus(2);
                    }else {
                        if(TimeUtil.compareTo(addDto.getEndTime(),new Date())){
                            //新改结束时间大于当前时间，状态改为生效
                            addDto.setStatus(1);
                            addDto.setStartTime(TimeUtil.dateToGTMString(new Date(),"yyyy-MM-dd HH:mm:ss"));
                        }else{
                            //新改结束时间小于当前时间，状态改为失效
                            addDto.setStatus(0);
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                discountMapper.savePackageDiscount(addDto);
            }
        }
        LogUtil.saveOperationLog("修改套餐信息",
                "套餐名称："+packageInfo.getPackageName()
                        +", 英文名称："+packageInfo.getEnglishName()
                        +", 繁体名称："+packageInfo.getTaiwanName()
                        +", 套餐有效期："+packageInfo.getDuration()+"天"
                        +", 美元价格："+packageInfo.getPrice()
                        +", 港币价格： "+packageInfo.getHkPrice()
                        +", 设备数量： "+packageInfo.getDeviceCount()
                        +", 苹果产品ID： "+packageInfo.getAppleProductId()
                        +", 状态为： "+(packageInfo.getStatus().equals("1")?"启用":"禁用"));
    }

    /**
     * 添加套餐折扣
     * @param dto
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public void addDiscount(AddDiscountDTO dto) {
        List<VpnPackageItemDO> packageInfoList = discountMapper.findPackageItemByPackageId(dto.getPackageId());
        if (packageInfoList == null){
            throw new GunsException(BizExceptionEnum.VPN_PACKAGE_DISCOUNT_PACKAGE_NOT_EXIST);
        }

        VpnPackageItemDO packageInfo = packageInfoList.get(0);

        dto.setStatus(1);
        dto.setDiscountPrice(packageInfo.getPrice() * dto.getDiscount());
        dto.setDiscountHkPrice(packageInfo.getHkPrice() * dto.getDiscount());
        try {
            if (!StringUtils.isEmpty(packageInfo.getEndTime())
                    && TimeUtil.compareTo(packageInfo.getEndTime(),dto.getStartTime())){
                throw new GunsException(BizExceptionEnum.VPN_PACKAGE_DISCOUNT_ERROR);
            }

            boolean compare = TimeUtil.compareTo(dto.getStartTime(),new Date());
            if (compare){
                dto.setStatus(2);
            }else{
                dto.setStartTime(TimeUtil.dateToGTMString(new Date(),"yyyy-MM-dd HH:mm:ss"));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        discountMapper.savePackageDiscount(dto);
    }

    /**
     * 获取短数据套餐列表
     * @return
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public Object shortVpnPackageList() {
        return discountMapper.findShortPackageList();
    }

    /**
     * 添加和修改用到的条件列表
     * @return
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public Object filterList() {
        FilterBO filterBO = new FilterBO();
        filterBO.setLastShowSort(discountMapper.lastShowSort());
        return filterBO;
    }

    /**
     * 自定义套餐列表
     * @return
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public Object packageList() {
        Paging<VpnPackageItemDO> paging = new Paging<>();
        paging.setItems(discountMapper.findPackageDiscountList());
        return paging;
    }

    /**
     * 查询套餐列表对象
     * @param packageId
     * @return
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public List<VpnPackageItemDO> findPackageItemByPackageId(Integer packageId) {
        return discountMapper.findPackageItemByPackageId(packageId);
    }
}
